import { normalize } from "./index";
import type { LineSeriesOption } from "echarts";

type LinesOptions = {
  xAxis: string[];
  series: LineSeriesOption[];
  legend: string[];
  formatter(params: any, index: number): string;
};

export class Lines<T> {
  private lines = new Map<keyof T, LineSeriesOption>();
  private readonly dimension: Record<string, keyof T>;
  private originalData: number[][] = [];
  private readonly xAxisField: keyof T;

  constructor(dimensionFieldMap: Record<string, keyof T>, xAxisField: keyof T) {
    this.dimension = dimensionFieldMap;
    this.xAxisField = xAxisField;
    this.initLinesFromDimension();
  }

  private initLinesFromDimension() {
    Object.keys(this.dimension).forEach((dimension) => {
      this.lines.set(this.dimension[dimension], { name: dimension, type: "line", stack: "Total", data: [] });
    });
  }

  public convertOptions(records: T[]): LinesOptions {
    records.forEach((league) => {
      this.lines.forEach((value, key) => {
        value.data!.push(Number(league[key]));
      });
    });

    this.normalizeLineData();
    return {
      xAxis: records.map((l) => `${l[this.xAxisField]}`),
      series: Array.from(this.lines.values()),
      legend: Object.keys(this.dimension),
      formatter: (params: any) => {
        let tipStr = "";
        params.forEach((item: any, index: number) => {
          // 使用原始数据替代标准化的数据
          const originalValue = this.originalData[index][item.dataIndex];
          tipStr += `${item.seriesName}: ${originalValue}<br/>`;
        });
        return tipStr;
      },
    };
  }

  private normalizeLineData() {
    this.lines.forEach((line) => {
      this.originalData.push([...(line.data as number[])]);
      line.data = normalize(line.data as number[]);
    });
  }
}
